package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.CommonError;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CourseMarketService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.DefaultEditorKit;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ybl
 * @date 2023/2/24 14:40
 * @description 课程信息管理业务接口实现类
 * @since version-1.0
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired(required = false)
    private CourseBaseMapper courseBaseMapper;

    @Autowired(required = false)
    private CourseMarketMapper courseMarketMapper;

    @Autowired(required = false)
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired(required = false)
    private CourseTeacherMapper courseTeacherMapper;

    @Autowired(required = false)
    private TeachplanMapper teachplanMapper;

    @Autowired(required = false)
    private TeachplanMediaMapper teachplanMediaMapper;

    @Autowired(required = false)
    private CourseMarketService courseMarketService;

    /**
     * @author ybl
     * @date 2023/2/24 15:02
     * @description 根据条件查询课程，返回分页信息
     * @param pageParams 分页参数
     * @param queryCourseParamsDto 条件
     * @return com.xuecheng.base.model.PageResult<com.xuecheng.content.model.po.CourseBase>
     * @since version-1.0
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        // 构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),
                CourseBase::getName, queryCourseParamsDto.getCourseName());
        // 构建查询条件，根据审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),
                CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        // 构建查询条件，根据发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),
                CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        // 构建分页对象，传入当前页码和每页记录数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> records = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集，并return
        return new PageResult<>(records, total, pageParams.getPageNo(), pageParams.getPageSize());
    }

    /**
     * @author ybl
     * @date 2023/2/28 14:59
     * @description 课程新增接口
     * @param companyId 教学机构id
     * @param addCourseDto 课程基本信息
     * @return com.xuecheng.content.model.dto.CourseBaseInfoDto 课程基本信息&课程营销信息
     * @since version-1.0
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        // 对数据进行封装，并进行持久化
        CourseBase courseBase = new CourseBase();
        // 将属性名一样的copy到courseBase中
        BeanUtils.copyProperties(addCourseDto, courseBase);
        // 设置审核状态
        courseBase.setAuditStatus("202002");
        // 设置发布状态
        courseBase.setStatus("203001");
        // 设置机构id
        courseBase.setCompanyId(companyId);
        // 向课程基本信息表插入信息
        int courseBaseInsert = courseBaseMapper.insert(courseBase);
        // 营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        courseMarket.setId(courseBase.getId());
        //收费课程必须写价格且价格大于0
        String charge = addCourseDto.getCharge();
        if (charge.equals("201001")) {
            BigDecimal price = courseMarket.getPrice();
            if (price == null || price.floatValue() <= 0) {
                throw new XueChengPlusException("课程设置收费,价格不能为空且必须大于0");
            }
        }
        // 向课程基本信息表插入信息
        int courseMarketInsert = courseMarketMapper.insert(courseMarket);
        if (courseBaseInsert <= 0 || courseMarketInsert <= 0) {
            throw new XueChengPlusException("新增课程信息失败");
        }
        // 组装返回结果
        return getCourseBaseInfo(courseBase.getId());
    }

    /**
     * @author ybl
     * @date 2023/2/28 15:55
     * @description 根据课程id查询课程基本信息，包括基本信息和营销信息
     * @param id 课程id
     * @return com.xuecheng.content.model.dto.CourseBaseInfoDto
     * @since version-1.0
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        if (courseBase != null) {
            BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
            //查询分类名称
            CourseCategory st = courseCategoryMapper.selectById(courseBase.getSt());
            if (st != null) {
                courseBaseInfoDto.setStName(st.getName());
            }
            CourseCategory mt = courseCategoryMapper.selectById(courseBase.getMt());
            if (mt != null) {
                courseBaseInfoDto.setMtName(mt.getName());
            }
        }
        return courseBaseInfoDto;
    }

    /**
     * @author ybl
     * @date 2023/3/1 11:54
     * @description 修改课程信息
     * @param companyId 机构id
     * @param editCourseDto 课程信息
     * @return com.xuecheng.content.model.dto.CourseBaseInfoDto
     * @since version-1.0
     */
    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        CourseBase courseBaseUpdate = courseBaseMapper.selectById(editCourseDto.getId());
        // 校验
        if (courseBaseUpdate == null) {
            XueChengPlusException.cast("课程不存在");
        }
        if (!courseBaseUpdate.getCompanyId().equals(companyId)) {
            XueChengPlusException.cast("只允许修改本机构的课程");
        }
        // 封装基本信息
        BeanUtils.copyProperties(editCourseDto, courseBaseUpdate);
        courseBaseUpdate.setChangeDate(LocalDateTime.now());
        // 修改课程基本信息表
        courseBaseMapper.updateById(courseBaseUpdate);
        // 营销表有则更新无则添加
        CourseMarket courseMarketUpdate = courseMarketMapper.selectById(editCourseDto.getId());
        // 校验
        if (courseMarketUpdate == null) {
            courseMarketUpdate = new CourseMarket();
        }
        // 封装营销信息
        courseMarketUpdate.setId(editCourseDto.getId());
        courseMarketUpdate.setCharge(editCourseDto.getCharge());
        BeanUtils.copyProperties(editCourseDto, courseMarketUpdate);
        //收费课程必须写价格且价格大于0
        String charge = courseMarketUpdate.getCharge();
        if (charge.equals("201001")) {
            BigDecimal price = courseMarketUpdate.getPrice();
            if (price == null || price.floatValue() <= 0) {
                throw new XueChengPlusException("课程设置收费,价格不能为空且必须大于0");
            }
        }
        // 修改/添加营销信息表
        boolean b = courseMarketService.saveOrUpdate(courseMarketUpdate);
        return getCourseBaseInfo(editCourseDto.getId());
    }

    /**
     * @author ybl
     * @date 2023/3/7 16:36
     * @description 删除课程相关的基本信息、营销信息、课程计划、课程教师信息,
     * @param id 为课程id
     * @since version-1.0
     */
    @Transactional
    @Override
    public void deleteCourseBase(Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase == null) {
            XueChengPlusException.cast(CommonError.PARAMS_ERROR);
            return;
        }
        String auditStatus = courseBase.getAuditStatus();
        // 课程为未审核方可删除 202003
        if (auditStatus.equals("202003") || auditStatus.equals("202004")) {
            XueChengPlusException.cast("课程未审核方可删除");
            return;
        }
        // 删除课程相关的基本信息、营销信息、课程计划、课程教师信息
        courseBaseMapper.deleteById(id);
        courseMarketMapper.delete(
                new LambdaQueryWrapper<CourseMarket>().eq(CourseMarket::getId, id)
        );
        teachplanMapper.delete(
                new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, id)
        );
        teachplanMediaMapper.delete(
                new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getCourseId, id)
        );
        courseTeacherMapper.delete(
                new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId, id)
        );
    }
}
